package ch02.error;

public class VolatileBankAccount {
	
	private int number;
	
	private volatile int balance;
	
	public VolatileBankAccount(int number,int balance){
		this.number = number;
		this.balance = balance;
	}
	
	public int getBalance(){
		return balance;
	}
	
	public void deposit(int amount){
		balance = balance + amount;
	}
	
	public void withdraw(int amount){
		balance = balance - amount;
	}
	
	public static void main(String[] args) throws InterruptedException {
		VolatileBankAccount account = new VolatileBankAccount(1, 1000);
		Thread t1 = new Thread(new Depositor(account, 100),"depositor");
		Thread t2 = new Thread(new Withdraw(account, 100),"depositor");
		t1.start();
		t2.start();
		t1.join();
		t2.join();
		System.out.println(account.getBalance());
	}
	
	static class Depositor implements Runnable{
		
		VolatileBankAccount account;
		
		int amount;
		
		public Depositor(VolatileBankAccount account,int amount) {
			this.account = account;
			this.amount = amount;
		}
		
		@Override
		public void run(){
			for (int i = 0; i < 1000000; i++) {
				account.deposit(amount);
			}
		}
		
	}
	
	static class Withdraw implements Runnable{
		
		VolatileBankAccount account;
		
		int amount;
		
		public Withdraw(VolatileBankAccount account,int amount) {
			this.account = account;
			this.amount = amount;
		}
		
		@Override
		public void run(){
			for (int i = 0; i < 1000000; i++) {
				account.withdraw(amount);
			}
		}
		
	}

}
